package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.sky.constant.MessageConstant.LOGIN_FAILED;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;
    /*
    * 1.根据code跟微信要openid
    * 2.将openid当作一个用户的唯一标识写入数据库
    * 3.将yonghuID获取后连openid一起返回交给controller层处理
    * @param userLoginDTO
    * @return
    * */

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.校验参数
        String code = userLoginDTO.getCode();
        if (StringUtils.isBlank(code)) {
            throw new LoginFailedException(LOGIN_FAILED);
        }

        //基于HttpClient根据code跟微信要openid
        String url = weChatProperties.getCode2SessionUrl();
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code);
        paramMap.put("grant_type",weChatProperties.getGrantType());
        String respStr = HttpClientUtil.doGet(url, paramMap);
        Map respMap = JSON.parseObject(respStr, Map.class);
        if (respMap.get("errcode")!=null){
            throw new LoginFailedException(LOGIN_FAILED);
        }
        String openid =(String)respMap.get("openid");

        //将yonghuID获取后连openid一起返回交给controller层处理
        //查询数据库是否有该openid的用户对象

        User dbUser=userMapper.findByOpenid(openid);
        if (dbUser==null){
            dbUser = new User();
            dbUser.setOpenid(openid);
            dbUser.setCreateTime(LocalDateTime.now());
            userMapper.insertUser(dbUser);//必须写id值
        }
        return dbUser;
    }
}
